﻿using Client.Framework;
using System;
using UnityEngine;
using UnityEngine.UI;

[DisallowMultipleComponent]
public class MyGoToPage : MonoBehaviour
{
    public Button m_LeftBtn;
    public Button m_RightBtn;
    public Action<int> OnChange;

    [SerializeField]
    [Range(1, byte.MaxValue)]
    private byte minValue;
    [SerializeField]
    [Range(1, byte.MaxValue)]
    private byte stepValue;

    [SerializeField]
    private bool mIsLoop;
    private int maxValue;
    private int curValue;

    public int CurValue
    {
        get { return curValue; }
        set
        {
            if (curValue != value)
            {
                curValue = value;
                RefreshData();
            }
        }
    }

    void Awake()
    {
        if (m_LeftBtn && m_RightBtn)
        {
            m_LeftBtn.onClick.AddListener(() => { OnPointerClick(m_LeftBtn); });
            m_RightBtn.onClick.AddListener(() => { OnPointerClick(m_RightBtn); });
        }
    }

    void OnDestroy()
    {
        if (m_LeftBtn && m_RightBtn)
        {
            m_LeftBtn.onClick.RemoveAllListeners();
            m_RightBtn.onClick.RemoveAllListeners();
        }
    }

    void OnPointerClick(Button button)
    {
        if (button == m_LeftBtn)
        {
            CurValue -= stepValue;
        }
        else if (button == m_RightBtn)
        {
            CurValue += stepValue;
        }
    }

    void OnSubmit(string text)
    {
        int.TryParse(text, out curValue);
        if (curValue < minValue)
        {
            curValue = minValue;
        }
        CurValue = curValue;
    }

    void RefreshData()
    {
        if (CurValue < minValue)
        {
            CurValue = mIsLoop ? maxValue : minValue;
        }
        else if (CurValue > maxValue)
        {
            CurValue = mIsLoop ? minValue : maxValue;
        }
        SetBtnState(); OnChange?.Invoke(CurValue);
    }

    void SetBtnState()
    {
        if (!mIsLoop)
        {
            Utility.SetActive(m_LeftBtn, CurValue > minValue);
            Utility.SetActive(m_RightBtn, CurValue < maxValue);
        }
    }

    public void SetData(int cur, int max)
    {
        if (cur > 0 && max > 0)
        {
            maxValue = max;
            CurValue = cur;
        }
    }
}